<template>
    <!-- 考试-题库 -->
    <div class="question-bank-list-wrap">
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item >
                    <!-- 创建时间 -->
                    <el-date-picker
                        v-model="searchForm.time"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        :picker-options="utils.intTimePickerOptions()"
                        @change="search">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-input
                        placeholder="请输入题干内容"
                        v-model="searchForm.content"
                        @keyup.enter.native="search"
                        clearable>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
            <div class="more-btns">
                <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link">更多操作</span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="add">新增</el-dropdown-item>
                        <el-dropdown-item command="import">批量导入</el-dropdown-item>
                        <el-dropdown-item command="batchDeletion">批量删除</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </el-row>
        <el-row class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
            <el-col :span="6">
                <div class="item-wrap" @click="searchForm.type=0" :class="searchForm.type==0 ? 'active' : ''">
                <div class="item-content">
                    <p class="item-value color-4">{{ questionStatistics.total }}</p>
                    <p class="item-title">试题总数</p>
                </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="item-wrap" @click="searchForm.type=1" :class="searchForm.type==1 ? 'active' : ''">
                <div class="item-content">
                    <p class="item-value color-3">{{ questionStatistics.trueOrFalse }}</p>
                    <p class="item-title">判断题</p>
                </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="item-wrap" @click="searchForm.type=2" :class="searchForm.type==2 ? 'active' : ''">
                <div class="item-content">
                    <p class="item-value color-1">{{ questionStatistics.radio }}</p>
                    <p class="item-title">单选题</p>
                </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="item-wrap" @click="searchForm.type=3" :class="searchForm.type==3 ? 'active' : ''">
                <div class="item-content">
                    <p class="item-value color-2">{{ questionStatistics.multipleSelection }}</p>
                    <p class="item-title">多选题</p>
                </div>
                </div>
            </el-col>
        </el-row>
        <div>
            <el-table
                v-loading="loading"
                ref="questionBankTableList"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="50"></el-table-column>
                <el-table-column label="题干" prop="content"></el-table-column>
                <el-table-column label="题型" prop="questionType" width="100">
                    <!-- 1判断题 2单选题 3多选题 -->
                    <template slot-scope="scope">
                        <p v-if="scope.row.questionType == 1">判断题</p>
                        <p v-else-if="scope.row.questionType == 2">单选题</p>
                        <p v-else>多选题</p>
                    </template>
                </el-table-column>
                <el-table-column label="来源" prop="source" width="120">
                    <!-- 1系统创建 2用户创建 -->
                    <template slot-scope="scope">
                        <p v-if="scope.row.source == 1">系统创建</p>
                        <p v-else>用户创建</p>
                    </template>
                </el-table-column>
                <el-table-column label="创建人" prop="createAccountName" width="250"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="200"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleDetail(scope.row)" type="text" size="small">详情</el-button>
                        <!-- 如果是平台管理员可以有系统默认题目的编辑和删除权限 -->
                        <span v-if="scope.row.source != 1 || $store.state.userinfo.role[0].id == 141" class="dividing-line">|</span>
                        <el-button v-if="scope.row.source != 1 || $store.state.userinfo.role[0].id == 141" @click="editQuestionInfo(scope.row)" type="text" size="small">编辑</el-button>
                        <span class="dividing-line">|</span>
                        <el-button @click="copyQuestionInfo(scope.row)" type="text" size="small">复制</el-button>
                        <span v-if="scope.row.source != 1 || $store.state.userinfo.role[0].id == 141" class="dividing-line">|</span>
                        <el-button v-if="scope.row.source != 1 || $store.state.userinfo.role[0].id == 141" @click="deleteQuestion(scope.row.id)" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="expand" width='1'>
                    <template slot-scope="scope">
                        <!-- 试题详情预览 -->
                        <question-view :info="scope.row"></question-view>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                background
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                :current-page.sync="currentPage"
                :page-sizes="[10, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <!-- 新增/编辑题目弹框 -->
        <el-dialog
            :close-on-click-modal="false"
            :title="dialogTitle"
            width="660px"
            top='10vh'
            v-if="dialogQuestionInfo"
            :visible.sync="dialogQuestionInfo"
            @close="closeQuestionInfo"
            v-dialogDrag>
            <question-info :oldInfo="currentQuestionInfo" :closeFun="closeQuestionInfo"></question-info>
        </el-dialog>
        <!-- 导入资产 -->
        <el-dialog
            :close-on-click-modal="false"
            title="批量导入试题"
            width="600px"
            top='10vh'
            v-if="dialogImportQuestion"
            :visible.sync="dialogImportQuestion"
            @close="closeImportQuestion"
            v-dialogDrag>
            <import-question :close="closeImportQuestion"></import-question>
        </el-dialog>
    </div>
</template>
<script>
import utils from '@/utils/util'
import { getQuestionListCount, getQuestionList, delQuestion, getQuestionOptionInfo } from '@/api/exam'
import QuestionInfo from './Dialog/QuestionInfo'
import QuestionView from './Dialog/QuestionView'
import ImportQuestion from './Dialog/ImportQuestion'

export default {
    components: {
        QuestionInfo,
        QuestionView,
        ImportQuestion
    },
    data() {
        return {
            utils: utils,
            loading: true,
            searchForm: {
                time: '',
                content: '',
                type: 0 // 题型
            },
            questionStatistics: {
                total: 0,
                trueOrFalse: 0,
                radio: 0,
                multipleSelection: 0
            },
            tableData: [],
            selectedQuestion: [], // 勾选的试题
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            dialogTitle: '新增试题',
            dialogQuestionInfo: false,
            dialogImportQuestion: false,
            currentQuestionInfo: {} // 当前操作的试题信息
        }
    },
    created() {
        this.search()
    },
    methods: {
        // 获取题目统计信息
        getQuestionCount() {
            let that = this
            getQuestionListCount({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                content: that.searchForm.content, // 题干内容
                account: that.$store.state.userinfo.accountName, // 当前登录账号
            }).then(res => {
                if(res.status === 200) {
                    that.questionStatistics.trueOrFalse = res.data['1']
                    that.questionStatistics.radio = res.data['2']
                    that.questionStatistics.multipleSelection = res.data['3']
                    that.questionStatistics.total = res.data['1'] + res.data['2'] + res.data['3']
                }
            })
        },
        // 获取列表数据
        getTableData(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            
            getQuestionList({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                content: that.searchForm.content, // 题干内容
                type: that.searchForm.type, // 题目类型（ 1判断题 2单选题 3多选题）
                account: that.$store.state.userinfo.accountName, // 当前登录账号
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize,
                queryType: 1
            }).then(res => {
                if(res.status === 200) {
                    that.tableData = res.data
                    that.total = res.total
                }
                that.loading = false
            })
            
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        formatDateTime: function(value) {
            return utils.ilinkTimeformat.format(new Date(value), 'yyyy-MM-dd hh:mm:ss')
        },
        search() {
            this.getQuestionCount()
            this.getTableData(1)
        },
        // 多选
        handleSelectionChange(val) {
            this.selectedQuestion = val
        },
        // 更多操作
        handleCommand(command) {
            let that = this

            switch (command) {
                case 'add':
                    that.addQuestion()
                    return false
                case 'import':
                    that.importQuestion()
                    return false
                case 'batchDeletion':
                    that.batchDeletion()
                    return false
                default:
                    return false
            }
        },
        // 新增试题
        addQuestion() {
            this.dialogTitle = '新增试题'
            this.currentQuestionInfo = {}
            this.dialogQuestionInfo = true
        },
        // 批量导入
        importQuestion() {
            this.dialogImportQuestion = true
        },
        // 批量删除
        batchDeletion() {
            let ids = []
            for(let i=0, len=this.selectedQuestion.length; i < len; i++) {
                ids.push(this.selectedQuestion[i].id)
            }
            if(ids.length > 0) {
                // 调用删除
                this.deleteQuestion(ids.join(','))
            } else {
                this.$message({
                    type: 'warning',
                    message: '请勾选你要删除的试题!'
                })
                return false
            }
        },
        // 查看详情
        handleDetail(row) {
            let that = this
            this.$refs.questionBankTableList.toggleRowExpansion(row)
        },
        // 编辑
        editQuestionInfo(info) {
            let that = this

            that.dialogTitle = '编辑试题'
            that.currentQuestionInfo = info
            // 获取题目选项信息
            getQuestionOptionInfo({
                questionId: info.id
            }).then(res => {
                if(res.status === 200) {
                    that.currentQuestionInfo.optionsStr = JSON.stringify(res.data)
                    that.dialogQuestionInfo = true
                }
            })
        },
        // 复制
        copyQuestionInfo(info) {
            let that = this
            let oldInfo = $.extend({}, info) 
            that.dialogTitle = '新增试题'
            that.currentQuestionInfo = oldInfo
            // 复制时清空id、createAccount、updateAccount
            that.currentQuestionInfo.id = ''
            that.currentQuestionInfo.createAccount = ''
            that.currentQuestionInfo.updateAccount = ''
            // 获取题目选项信息
            getQuestionOptionInfo({
                questionId: info.id
            }).then(res => {
                if(res.status === 200) {
                    that.currentQuestionInfo.optionsStr = JSON.stringify(res.data)
                    that.dialogQuestionInfo = true
                }
            })
        },
        // 删除
        deleteQuestion(ids) {
            let that = this
            this.$confirm("确定删除？", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                roundButton: true
            }).then(() => {
                delQuestion({
                    ids: ids
                }).then(res => {
                    if(res.status === 200) {
                        that.$message.success('删除成功！')
                        // 刷新列表和统计
                        that.search()
                    }
                })
            }).catch(() => {

            })
        },
        // 关闭弹框
        closeQuestionInfo(refresh) {
            this.dialogQuestionInfo = false
            if(typeof(refresh) === 'boolean' && refresh) {
                this.getQuestionCount()
                this.getTableData(this.currentQuestionInfo.id?'':1)
            }
        },
        // 关闭导入弹框
        closeImportQuestion(refresh) {
            this.dialogImportQuestion = false
            if(typeof(refresh) === 'boolean' && refresh) {
                this.search()
            }
        }
    },
    computed: {
        typeChange() {
            return this.searchForm.type
        }
    },
    watch: {
        typeChange(val, oldVal) {
            this.getTableData(1, 10)
        }
    }
}
</script>
